<template>
  <div class="building-container">
    <!-- 搜索区域 -->
    <div class="search-container">
      <div class="search-label">企业名称：</div>
      <el-input v-model.trim="enterpriseName" clearable placeholder="请输入内容" class="search-main" />
      <el-button type="primary" @click="searchEnterprise">查询</el-button>
    </div>
    <div class="create-container">
      <el-button v-isShowEL="'park:enterprise:add_edit'" type="primary" @click="$router.push('/addenterprise')">添加企业</el-button>
    </div>
    <!-- 表格区域 -->
    <div class="table">
      <el-table style="width: 100%" :data="parkInfo" type="expand" @expand-change="expendChangeFn">
        <el-table-column type="expand">
          <template slot-scope="props">
            <el-table
              ref="filterTable"
              :data="props.row.rantList"
              style="width: 100%"
            >
              <el-table-column
                prop="buildingName"
                label="租赁楼宇"
              />
              <el-table-column
                prop="startTime"
                label="租赁起始时间"
              />
              <el-table-column
                prop="status"
                label="合同状态"
              >
                <template slot-scope="scope">
                  <el-tag :type="tagType[scope.row.status]">{{ rantStatus[scope.row.status] }}</el-tag>
                </template>
              </el-table-column>
              <el-table-column
                fixed="right"
                label="操作"
                width="120"
              >
                <template slot-scope="scope">
                  <el-button
                    type="text"
                    size="small"
                    :disabled="scope.row.renewFlag === 1"
                  >
                    续租
                  </el-button>

                  <el-button
                    type="text"
                    size="small"
                    :disabled="scope.row.status === 3"
                    @click="rentTerminationFn(scope.row.id)"
                  >
                    退租
                  </el-button>

                  <el-button
                    type="text"
                    size="small"
                    :disabled="!(scope.row.status === 3)"
                  >
                    删除
                  </el-button>

                </template>
              </el-table-column>
            </el-table>
          </template>
        </el-table-column>
        <el-table-column type="index" label="序号" />
        <el-table-column label="企业名称" width="320" prop="name" />
        <el-table-column label="联系人" prop="contact" />
        <el-table-column
          label="联系电话"
          prop="contactNumber"
        />
        <el-table-column label="操作">
          <template slot-scope="scope">
            <el-button size="mini" type="text" @click="showrent(scope.row)">添加合同</el-button>
            <el-button size="mini" type="text" @click="$router.push(`/showRant?id=${scope.row.id}`)">查看</el-button>
            <el-button size="mini" type="text">编辑</el-button>
            <el-button size="mini" type="text">删除</el-button>
          </template>
        </el-table-column>
      </el-table>
    </div>
    <!-- 分页 -->
    <div class="page-container">
      <el-pagination
        layout="total, prev, pager, next, sizes"
        :total="total"
        :page-sizes="[2,4,6,8]"
        :page-size="pageSize"
        :current-page.sync="page"
        @current-change="handleCurrentChange"
        @size-change="handleSizeChange"
      />
    </div>
    <!-- 弹出框（添加合同） -->
    <el-dialog
      title="提示"
      :visible.sync="dialogVisible"
      width="30%"
      :before-close="handleClose"
    >
      <el-form ref="addrentform" :model="addrentinfo" label-width="80px" label-position="top" :rules="addrentRules">

        <el-form-item label="楼宇信息" prop="buildingId">
          <el-select v-model="addrentinfo.buildingId" placeholder="请选择楼宇信息">
            <el-option v-for="item in buildinfo" :key="item.id" :label="item.name" :value="item.id" />
          </el-select>
        </el-form-item>

        <el-form-item label="租赁起止日期" prop="buildDate">
          <el-date-picker
            v-model="addrentinfo.buildDate"
            type="daterange"
            range-separator="至"
            start-placeholder="开始日期"
            end-placeholder="结束日期"
            value-format="yyyy-MM-dd"
          />
        </el-form-item>

        <el-form-item label="租赁合同" prop="contractId">
          <el-upload
            class="upload-demo"
            action="*"
            :http-request="addrentFn"
            :limit="1"
            :before-upload="beforeAvatarUpload"
            :file-list="addrentList"
          >
            <el-button size="small" type="primary">点击上传</el-button>
            <div slot="tip" class="el-upload__tip">只能上传pdf/doc文件，且不超过5mb</div>
          </el-upload>
        </el-form-item>

      </el-form>

      <span slot="footer" class="dialog-footer">
        <el-button @click="failrentFn">取 消</el-button>
        <el-button type="primary" @click="rentInfoFN">确 定</el-button>
      </span>
    </el-dialog>
  </div>
</template>

<script>
import { addrentApi, expandViewApi, getEnterpriseAPI, rentTerminationApi, uploadIndustryFileAPI } from '@/apis/Park'
import { getbuildInfoApi } from '@/apis/building'
import { Message } from 'element-ui'
// import { Message } from 'element-ui'

export default {
  data() {
    return {
      // 当前页面
      page: 1,
      // 每一页的数量
      pageSize: 2,
      // 页面展示数据
      parkInfo: [],
      // 全部数据
      total: null,
      // 企业名称
      enterpriseName: '',
      // 添加合同弹出框
      dialogVisible: false,
      // 添加合同信息
      addrentinfo: {
        buildingId: '',
        buildDate: [],
        contractUrl: '',
        contractId: '',
        enterpriseId: ''
      },
      // 楼宇信息
      buildinfo: [],
      addrentList: [],
      // 校验规则
      addrentRules: {
        buildingId: [
          { required: true, message: '请输入楼宇名称', trigger: ['change', 'blur'] }
        ],
        buildDate: [
          { required: true, message: '请选择起止日期', trigger: 'blur' }
        ],
        contractId: [
          { required: true, message: '请选择文件', trigger: 'blur' }
        ]

      },
      // 展开显示数据
      rentalInformation: [],
      // 合同状态
      rantStatus: {
        0: '待生效',
        1: '生效中',
        2: '已到期',
        3: '已退租'
      },
      // 组件不同样式
      tagType: {
        0: 'success',
        1: 'info',
        2: 'warning',
        3: 'danger'
      }

    }
  },
  created() {
    this.getEnterpriseList()
  },
  methods: {
    // 获取数据列表
    async getEnterpriseList() {
      const res = await getEnterpriseAPI({
        page: this.page,
        pageSize: this.pageSize,
        name: this.enterpriseName
      })
      this.total = res.data.total
      this.parkInfo = res.data.rows.map(item => {
        return {
          ...item,
          rantList: []
        }
      })
    },
    // 获取当前页面页码
    handleCurrentChange(val) {
      this.page = val
      this.getEnterpriseList()
    },
    // 获取每页条数
    handleSizeChange(val) {
      this.pageSize = val
      this.getEnterpriseList()
    },
    // 查询条数
    searchEnterprise() {
      this.page = 1
      this.getEnterpriseList()
    },
    // 关闭按钮
    handleClose() {
      this.$confirm('确认关闭？').then(() => {
        this.dialogVisible = false
      })
    },
    // 查询楼宇信息
    async getbuildingInfo() {
      const res = await getbuildInfoApi({
        page: 1,
        pageSize: 1
      })

      const total = res.data.total

      const res2 = await getbuildInfoApi({
        page: 1,
        pageSize: total
      })

      this.buildinfo = res2.data.rows
    },
    // 上传合同附件
    async addrentFn(file) {
      // 附件对象
      const formdataFiltDate = new FormData()

      formdataFiltDate.append('file', file.file)
      formdataFiltDate.append('type', 'contract')

      const res = await uploadIndustryFileAPI(formdataFiltDate)
      console.log(res)

      // 获取附件id和url
      this.addrentinfo.contractUrl = res.data.url
      this.addrentinfo.contractId = res.data.id

      // 给上传文件数组赋值
      this.addrentList = [
        { name: res.data.name, url: res.data.url }
      ]

      this.$refs.addrentform.validateField('contractId')
    },
    // 上传之前限制文件类型
    beforeAvatarUpload(file) {
      // 文件类型数组
      const fileType = ['application/pdf', 'application/msword', 'application/vnd.openxmlformats-officedocument.wordprocessingml.document']
      const isType = fileType.includes(file.type)
      if (!isType) {
        this.$message.error('上传的文件只能是pdf/doc/docx格式!')
        return false
      }

      // 文件大小 5mb以内
      const isLt5M = file.size / 1024 / 1024 < 5
      if (!isLt5M) {
        this.$message.error('上传的文件大小要在5mb以内！')
        return false
      }

      return isType && isLt5M
    },
    // 点击弹框
    showrent(row) {
      this.dialogVisible = true
      // 查询楼宇信息
      this.getbuildingInfo()
      console.log(row)
      this.addrentinfo.enterpriseId = row.id
    },
    // 点击确认添加合同信息
    async rentInfoFN() {
      this.$refs.addrentform.validate(async(isFlag) => {
        if (!isFlag) {
          return Message.error('请输入正确的信息')
        }
        const obj = {
          ...this.addrentinfo,
          type: 0
        }
        obj.startTime = this.addrentinfo.buildDate[0]
        obj.endTime = this.addrentinfo.buildDate[1]
        delete obj.buildDate

        await addrentApi(obj)
        this.dialogVisible = false
        this.getEnterpriseList()
      })
    },
    // 重置表单
    failrentFn() {
      this.$refs.addrentform.resetFields()

      // 获取附件id和url
      this.addrentinfo.contractUrl = ''
      this.addrentinfo.contractId = ''

      // 给上传文件数组赋值
      this.addrentList = []
    },
    // 某一行被展开触发
    async expendChangeFn(row, rows) {
      const isExd = rows.includes(row)
      if (isExd) {
        const res = await expandViewApi(row.id)
        row.rantList.push(...res.data)
      } else {
        row.rantList = []
      }
    },
    ddg(row) {
      console.log(row)
    },
    // 退租
    rentTerminationFn(id) {
      this.$confirm('确定要退租嘛').then(async() => {
        const res = await rentTerminationApi(id)
        Message.success(res.msg)
        this.getEnterpriseList()
      })
    }
  }
}
</script>

<style lang="scss" scoped>
.department-container {
  padding: 10px;
}

.search-container {
  display: flex;
  align-items: center;
  border-bottom: 1px solid rgb(237, 237, 237, .9);
  ;
  padding-bottom: 20px;

  .search-label {
    width: 100px;
  }

  .search-main {
    width: 220px;
    margin-right: 10px;
  }
}
.create-container{
  margin: 10px 0px;
}
.page-container{
  padding:4px 0px;
  text-align: right;
}
.form-container{
  padding:0px 80px;
}

</style>
